<?php namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Services\UserManager;
use App\Http\Services\Wechat\WechatModelMsg;
use App\Orders;
use App\User;
use EasyWeChat\Payment\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class PaymentController extends Controller
{
    /**
     * 微信内支付
     */
    public function payByWechatJsApi(Request $request){
        $orderNum = $request->get('order_num');

        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level'=>'error','message'=>'请先登录','data'=>'']);

        /** @var Orders $thatOrder */
        $thatOrder = Orders::whereOrderNum($orderNum)->first();
        if(!$thatOrder)
            return response()->json(['level'=>'error','message'=>'当前订单不存在','data'=>'']);

        $openId = $user->openid;
        $app = app("wechat");
        $attributes = [
            'trade_type'       => 'JSAPI',
            'body'             => 'ZoomYoung个定商城',
            'detail'           => '定制商品购买付费',
            'out_trade_no'     => $orderNum,
            'total_fee'        => round((float)$thatOrder->s_amount * 100,2),
            'notify_url'       => route('Api.Payment.wechatPayCallBack'),
            'openid'           => $openId,
        ];
        $payment = $app->payment;
        $order = new Order($attributes);
        $result = $payment->prepare($order);
        if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
            $prepayId = $result->prepay_id;
            $json = $payment->configForPayment($prepayId);
            return response()->json(['level'=>'success','message'=>trans('获取支付信息成功'),'data'=>json_decode($json)]);
        }else{
            return response()->json(['level'=>'error','message'=>'创建支付信息失败','data'=>$result]);
        }
    }

    public function checkPayResult(Request $request){
        $orderNum = $request->get('order_num');

        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level'=>'error','message'=>'请先登录','data'=>'']);

        $thatOrder = Orders::whereOrderNum($orderNum)->first();
        if(!$thatOrder)
            return response()->json(['level'=>'error','message'=>'当前订单不存在','data'=>'']);

        if($thatOrder->ispay == 0){
            return response()->json(['level'=>'success','message'=>'no_pay','data'=>'']);
        }elseif($thatOrder->ispay == 1){
            return response()->json(['level'=>'success','message'=>'has_pay','data'=>'']);
        }
    }

    public function wechatPayCallBack(){
        $app = app("wechat");
        $response = $app->payment->handleNotify(function($notify, $successful){
            Log::info('order_num=>'.$notify->out_trade_no);

            /** @var Orders $thatOrder */
            $thatOrder= Orders::whereOrderNum($notify->out_trade_no)->first();
            if (!$thatOrder) {
                return 'Order not exist.';
            }

            if ($thatOrder->ispay == 1) {
                return true;
            }

            if ($successful) {
                $thatOrder->paytime = date('Y-m-d H:i:s',time());
                $thatOrder->ispay   = 1;
                $thatOrder->pay_type = 'wxpay';
                $thatOrder->status   = 1;
                $thatOrder->save();

                WechatModelMsg::sendOrderMsg($thatOrder->order_num);
                //发送微信模版消息
                WechatModelMsg::sendMsgToManager("orn9vwAJuQMaGBV5gXHgkebTHP-0",$thatOrder->order_num);
                WechatModelMsg::sendMsgToManager("orn9vwBZKVA94mZTzR2nhbTI4Mbs",$thatOrder->order_num);

                return true;
            } else {
                $thatOrder->ispay = 0;
                $thatOrder->save();

                return 'fail.';
            }



        });

        return $response;
    }
}